﻿using System.Linq;

namespace WebStudio.Mvc.MvcPager
{
    /// <summary>
    /// IQueryable扩展函数
    /// </summary>
    public static class IQueryableExtension
    {
        #region 转换IQueryable<T>对象为PagedList<T>
        /// <summary>
        /// 转换IQueryable对象为PagedList
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="allItems"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static PagedList<T> ToPagedList<T>(this IQueryable<T> allItems, int pageIndex, int pageSize)
        {
            if (pageIndex < 1)
                pageIndex = 1;
            var itemIndex = (pageIndex - 1) * pageSize;
            var pageOfItems = allItems.Skip(itemIndex).Take(pageSize);
            var totalItemCount = allItems.Count();
            return new PagedList<T>(pageOfItems, pageIndex, pageSize, totalItemCount);
        }
        #endregion
    }
}
